package org.example.util;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author zengxiaoyu
 * @date 2025/9/3 11:25
 */
public class Opt<T> {

    private T t;

    private Opt(T t) {
        this.t = t;
    }

    public static <T> Opt<T> of(T t) {
        return new Opt<>(t);
    }



    public<V> Opt<V> exec(Function<T,V>  func){
          return isPresent()?Opt.of(func.apply(t)):Opt.of(null);
    }

    public Opt<T> action(Consumer<T> action){
        if(isPresent()){
            action.accept(t);
        }
        return this;
    }


    public boolean isPresent() {
        return t != null;
    }


    public T get() {
        return t;
    }

    public T orElse(T other) {
        return isPresent()?t:other;
    }

    public<V> V orElseCast(V other) {
        return isPresent()? (V) t :other;
    }

    public T orElseGet(Supplier<T> supplier) {
        return isPresent()?t:supplier.get();
    }

    public<V> Opts<V> ofs(Function<T, List<V>> function) {
        return isPresent()?Opts.of(function.apply(t)):Opts.empty();
    }
}
